var log4js = require('log4js');
const express = require('express');
const expressStatic = require('express-static');
const bodyParser = require('body-parser'); //只能解析数据类型的post请求，无法处理文件类
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const multer = require('multer');
const consolidate = require('consolidate');//用来适配模板引擎
const ejs = require('ejs');
const expressRoute = require('express-route');
const responseBuilder = require('./libs/response-data');
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt'); //jwt用来验证前端请求
const Sequelize     = require('sequelize');
const SequelizeUtil = require('./libs/db-sequelize-util');

const jwtSecret = "thisisLeeyaoTokenSecret";
var app = new express();
var log = log4js.getLogger("app");
app.use(log4js.connectLogger(log4js.getLogger("http"), { level: 'auto' }));

//
var objMulter = new multer({dest:"./www/upload/"});

//1、解析cookie
var encryKey = "dsfkejljsodjflmand#d";
app.use(cookieParser(encryKey));
//2、使用session
var keyArr = [];
for (let i = 0; i < 10000; i++) {
    keyArr.push('sign_'+Math.random());
}
//这只session值，加密key, 有效时间20分钟
app.use(cookieSession({
    name : 'ly_session_id',
    keys : keyArr,
    maxAge : 20 * 3600 * 1000
}));
//3、POST数据， body-parser无法处理文件请求
app.use(bodyParser.urlencoded({extended : false}));

//post文件处理
//3.1 初始new multer({dest:"./www/upload/"})表示上传到这个文件夹里面
app.use(objMulter.any());

/**
 * 4、模板引擎的使用consolidate
 *  4.1 哪种模板引擎
 *  4.2 模板引擎文件位置
 *  4.3 输出什么东西
 */
app.set('view engine', 'html');
app.set('views', 'view');
app.engine('html', consolidate.ejs);

app.get('/', function(req, res) {
    res.render('index.ejs', {name : "leeyao"});
});

//设置允许跨域访问 ： 解决xmlhttprequest blocked by cors policy:No 'Access-control-Allow-Origin'问题
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });

//用户请求,请求跟目录
// app.use('/', function(req, res) {
//     console.log(req.query, req.body, req.cookies, req.session);
//     console.log(req.files);
// });

//5、route
let userRouter = require('./route/user');
let restfulRouter = require('./route/restful/index');

/**
 * ********************************  backend manager routers
 */
// var blogRouter = express.Router();
app.use('/user/', userRouter());
app.use('/blog/', require('./route/blog')());
app.use('/admin/', require('./route/admin/admin.js')());

/**
 * ********************************  restful api routers
 * 设置哪些router需要验证
 * 验证token, 
 * 1、判断用户是否登录
 * 2、如果没有，查询数据库，成功生成token,返回给用户
 * 3、否则提示用户没有登录
 * 
 */
//使用中间件验证token合法性
app.use(expressJwt ({
    secret:  jwtSecret 
}).unless({
    path: ['/login', '/getToken', '/api/user/signin', '/api/getTest', '/api/postTest']  //除了这些地址，其他的URL都需要验证
}));
//拦截器
app.use(function (err, req, res, next) {
    //当token验证失败时会抛出如下错误
    // 拿取token 数据 按照自己传递方式写
    var token = req.body.token || req.query.token || req.headers['x-access-token'];
    console.log('拦截token是否有效', token);
    if (token) {      
        // 解码 token (验证 secret 和检查有效期（exp）)
        jwt.verify(token, jwtSecret, function(err, decoded) {      
              if (err) {
                  console.log('jwt.verify', err);

                return res.json({ success: false, message: '无效的token.' });    
              } else {
                // 如果验证通过，在req中写入解密结果
                req.decoded = decoded;  
                //console.log(decoded)  ;
                next(); //继续下一步路由
          }
        });
      } else {
        // 没有拿到token 返回错误 
        return res.status(403).send(responseBuilder.getResponse('0', '请先登录', {}));
    }

});
const User = SequelizeUtil.define('user', {
    username : {type : Sequelize.STRING}, 
    password : {type : Sequelize.STRING},}, {
        freezeTableName : true,
        tableName : 'user_table',
        createdAt : false,
        updatedAt : false
    });
app.post('/getToken', (req, res)=>{

    let username = req.body.username;
    let password = req.body.password;

    User.findOne({
        where : {username : username},
    }).then(user => {
        let pass = user.get('password');
        console.log(user.get('password'));
        if (password === pass) {
            let token = jwt.sign({
                data: 'user_auth'
                }, jwtSecret, { expiresIn: 60*60*100 });
                return res.status(200).send(responseBuilder.getResponse('0', '', {token : token}));
        }else {
            return res.status(200).send(responseBuilder.getResponse('0', '密码错误', {}));
        }
    })
    .catch(err => {
        console.error('findOne error ---> ', err);
        return res.status(200).send(responseBuilder.getResponse('0', '登录失败', {})); 
    });

});
// app.use(jwt({ secret: 'shhhhhhared-secret'}).unless({path: ['/token']}));
app.use('/api/', restfulRouter());


//6、static数据,外部访问静态数据
app.use(expressStatic('./www'));

module.exports = app;